﻿using Hangfire.Logging;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tingjian.gas.service.Consts;
using Tingjian.gas.service.Data;
using Tingjian.gas.service.Product;

namespace Tingjian.gas.service.BackgroundJobs.Jobs.NetCoreJobs
{
    public class ConsumerRedisJob : BackgroundService
    {
        public ILogger<ConsumerRedisJob> _logger;
        private readonly IProductAppService _productAppService;

        public ConsumerRedisJob(IProductAppService productAppService, ILogger<ConsumerRedisJob> logger)
        {
            _productAppService = productAppService;
            //Logger = Logger<ConsumerRedisJob>.Instance;
            _logger = logger;
        }


        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {


            await Task.Delay(10 * 1000, stoppingToken);

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var msg = $"CurrentTime:{DateTime.Now.ToString(FormatConsts.DatetimeFormatStr)}, 轮训消费redis数据!";

                    _logger.LogInformation(msg);

                   var res = await _productAppService.ConsumerRedisListAsync();
                    if (!res)
                    {
                        await Task.Delay(60 * 1000, stoppingToken);//如果没有可消费的, 休眠60s
                    }

                    await Task.Delay(1 * 1, stoppingToken);

                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                    await Task.Delay(60 * 1000, stoppingToken);
                }


            }
        }
    }
}
